package com.ktjy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjy.pojo.Customer;
import com.ktjy.pojo.Orders;
import com.ktjy.pojo.OrdersLine;
import com.ktjy.service.ICustomerService;
import com.ktjy.service.IOrdersLineService;
import com.ktjy.service.IOrdersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jjx
 * @since 2025-01-16
 */
@Controller
@RequestMapping("/orders")
public class OrdersController {
    Logger logger = LoggerFactory.getLogger(OrdersController.class);

    @Autowired
    IOrdersService iOrdersService;
    @Autowired
    ICustomerService iCustomerService;
    @Autowired
    IOrdersLineService iOrdersLineService;

    @RequestMapping("/list")
    public String list(Orders orders,
                       @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                       Model model) {
        try {
            //组装分页条件
            Page<Orders> page=new Page<>(pageIndex,pageSize);
            //组装过滤条件 动态sql
            QueryWrapper qw=new QueryWrapper();
            qw.like("odr_customer",orders.getOdrCustomer());

            //调用分页方法
            IPage pager=iOrdersService.page(page, qw);
            model.addAttribute("pager", pager);

            //回显数据
            model.addAttribute("condition", orders);

            //查询客户信息
            Customer customer=iCustomerService.getById(orders.getOdrCustomer());
            model.addAttribute("customer",customer);
        } catch (Exception e) {
            logger.error("OrdersController 中的 list 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "order/list";
    }

    /**
     * 跳转到新增页面
     *
     * @return
     */
    @GetMapping("/view")
    public String view(@RequestParam("id") Long id,Model model) {
        try {
            //根据订单编号，查询订单信息
            Orders orders=iOrdersService.getById(id);
            model.addAttribute("orders",orders);

            //根据订单编号，查询订单明细
            List<OrdersLine> ordersLineList=
                    iOrdersLineService.getOrdersLineByOrderId(id);
            model.addAttribute("ordersLineList",ordersLineList);
        } catch (Exception e) {
            logger.error("OrdersController 中的 view 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "order/view";
    }
}
